<?php

namespace Beerus\Modules\DecoCompany\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\service\DecoCompany\DecoGeneralConfig\DecoServiceTag as sDecoServiceTag;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\DecoServiceTag as mDecoServiceTag;
use Illuminate\Support\MessageBag;

class DecoServiceTagController
{
    // 列表
    public function index(Request $request,Content $content) {
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);

        $configList = mDecoServiceTag::listByCondition([
            'data_status' => mDecoServiceTag::STATUS_NORMAL,
            'LIMIT' => [($page - 1) * $pageSize, $pageSize ],
        ]);
        $total = mDecoServiceTag::countByCondition([
            'data_status' => mDecoServiceTag::STATUS_NORMAL,
        ]);
        $gridModel = new pGridDataModel($configList, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->column("id", 'ID');
                $grid->column("name", '名称');
                $grid->column("desc", '描述');
                $grid->column("edit_time", '操作时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->edit_time);
                });
                $grid->column("admin_id", '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                });
            });

        $tab = new Tab();
        $tab->add('装修服务标签配置列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('装修服务标签配置列表')
            ->description(' ')
            ->breadcrumb(['text' => '装修服务标签配置列表']);
    }

    // 编辑
    public function edit(Content $content, $id = 0)
    {
        if($id == 0) {
            return $content
                ->header('装修服务标签配置 - 新增')
                ->breadcrumb([
                    'text' => '装修服务标签配置列表',
                    'url' => '/DecoCompany/decoServiceTag/',
                ])
                ->body(self::editAction($id));
        } else {
            return $content
                ->header('装修服务标签配置 - 编辑')
                ->breadcrumb([
                    'text' => '装修服务标签配置列表',
                    'url' => '/DecoCompany/decoServiceTag/',
                ])
                ->body(self::editAction($id));
        }
    }

    public function editAction($id)
    {
        if($id == 0) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = mDecoServiceTag::getByCondition(['id' => $id]);
            $form = new Form($data);
            $form->hidden('id');
        }

        $form->text('name', '名称')->setWidth(4, 2)
            ->required('不能为空')->help("最多" . sDecoServiceTag::MAX_COUNT . "个配置项，每项最多" . sDecoServiceTag::NAME_MAX_LENGTH . "个汉字");
        $form->textarea('desc', '描述')->setWidth(4, 2)->required()->attribute('maxlength', 50);
        $form->action('/admin/DecoCompany/decoServiceTag/save');
        return $form->render();
    }

    // 提交
    public function editSubmit(Request $request)
    {
        $request['name'] = trim($request['name']);
        $verifyNameRes = sDecoServiceTag::verifyName($request['name'], $request['id']);
        if ($verifyNameRes['code'] != 1) {
            $error = new MessageBag([
                'title' => $verifyNameRes['msg']
            ]);
            return back()->with(compact('error'));
        }

        $data = [
            'id' => $request['id'],
            'name' => $request['name'],
            'desc' => $request['desc'],
            'admin_id' => Admin::user()->id,
        ];

        if (!empty($request['id'])) {
            $data['edit_time'] = time();
            $rs = mDecoServiceTag::updateInfo($data, [
                'id' => $request['id']
            ]);
        } else {
            $verifyCountRes = sDecoServiceTag::verifyCount();
            if ($verifyCountRes['code'] != 1) {
                $error = new MessageBag([
                    'title' => $verifyCountRes['msg']
                ]);
                return back()->with(compact('error'));
            }
            $data['add_time'] = time();
            $rs = mDecoServiceTag::addInfo($data);
        }
        if ($rs) {
            if (!empty($request['id'])) {
                $title = '修改成功';
            } else {
                $title = '添加成功';
            }
            $success = new MessageBag([
                'title' => $title
            ]);
            return redirect('/admin/DecoCompany/decoServiceTag')->with(compact('success'));
        } else {
            if (!empty($request['id'])) {
                $title = '修改失败';
            } else {
                $title = '添加失败';
            }
            $error = new MessageBag([
                'title' => $title
            ]);
            return back()->with(compact('error'));
        }
    }

    public function delete($id)
    {
        if (sDecoServiceTag::isRelatedCompany($id)) {
            return response()->json([
                'status' => false,
                'message' => "已有装修公司选择此项，无法删除",
            ]);
        }

        $update_data = [
            'data_status' => mDecoServiceTag::STATUS_DELETE,
            'admin_id' => Admin::user()->id,
        ];
        if (!mDecoServiceTag::updateInfo($update_data, ['id' => $id])) {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
        return response()->json([
            'status' => true,
            'message' => "删除成功",
        ]);
    }
}
